<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>新闻首页</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background-color: #f5f5f5;
            color: #333;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px 0;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
        }

        .header h1 {
            text-align: center;
            font-size: 2.5em;
            margin-bottom: 20px;
        }

        .search-section {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            margin: 20px auto;
            max-width: 600px;
        }

        .search-form {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }

        .add-news-section {
            text-align: center;
        }

        .add-btn {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            color: white;
            border: none;
            padding: 12px 25px;
            border-radius: 8px;
            font-size: 16px;
            cursor: pointer;
            transition: transform 0.2s;
        }

        .add-btn:hover {
            transform: translateY(-2px);
        }

        .search-input {
            flex: 1;
            padding: 15px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 16px;
            transition: border-color 0.3s;
        }

        .search-input:focus {
            outline: none;
            border-color: #667eea;
        }

        .search-btn {
            padding: 15px 30px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            cursor: pointer;
            transition: transform 0.2s;
        }

        .search-btn:hover {
            transform: translateY(-2px);
        }

        .news-section {
            background: white;
            margin: 20px auto;
            border-radius: 10px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            overflow: hidden;
        }

        .section-title {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            font-size: 1.5em;
            text-align: center;
        }

        .news-list {
            padding: 20px;
        }

        .news-item {
            border-bottom: 1px solid #e0e0e0;
            padding: 20px 0;
            transition: background-color 0.3s;
            position: relative;
        }

        .news-item:hover {
            background-color: #f8f9fa;
        }

        .news-item:last-child {
            border-bottom: none;
        }

        .news-content {
            padding-right: 120px;
        }

        .news-actions {
            position: absolute;
            right: 20px;
            top: 50%;
            transform: translateY(-50%);
            display: flex;
            gap: 10px;
        }

        .action-btn {
            padding: 8px 15px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s;
        }

        .edit-btn {
            background: #007bff;
            color: white;
        }

        .edit-btn:hover {
            background: #0056b3;
        }

        .delete-btn {
            background: #dc3545;
            color: white;
        }

        .delete-btn:hover {
            background: #c82333;
        }

        .news-title {
            font-size: 1.3em;
            font-weight: bold;
            color: #333;
            margin-bottom: 10px;
            cursor: pointer;
            transition: color 0.3s;
        }

        .news-title:hover {
            color: #667eea;
        }

        .news-meta {
            display: flex;
            gap: 20px;
            color: #666;
            font-size: 0.9em;
            margin-bottom: 10px;
        }

        .news-summary {
            color: #666;
            line-height: 1.6;
        }

        .pagination {
            display: flex;
            justify-content: center;
            gap: 10px;
            padding: 20px;
        }

        .page-btn {
            padding: 10px 15px;
            border: 1px solid #ddd;
            background: white;
            cursor: pointer;
            border-radius: 5px;
            transition: all 0.3s;
        }

        .page-btn:hover {
            background: #667eea;
            color: white;
        }

        .page-btn.active {
            background: #667eea;
            color: white;
        }

        .loading {
            text-align: center;
            padding: 40px;
            color: #666;
        }

        .error {
            background: #ffebee;
            color: #c62828;
            padding: 15px;
            border-radius: 5px;
            margin: 20px;
            text-align: center;
        }

        .no-data {
            text-align: center;
            padding: 40px;
            color: #666;
            font-size: 1.1em;
        }

        /* 模态框样式 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
        }

        .modal-content {
            background-color: white;
            margin: 5% auto;
            padding: 30px;
            border-radius: 10px;
            width: 80%;
            max-width: 600px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.3);
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 2px solid #f0f0f0;
        }

        .modal-title {
            font-size: 1.5em;
            font-weight: bold;
            color: #333;
        }

        .close {
            color: #aaa;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
        }

        .close:hover {
            color: #000;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
            color: #333;
        }

        .form-input {
            width: 100%;
            padding: 12px;
            border: 2px solid #e0e0e0;
            border-radius: 5px;
            font-size: 16px;
            transition: border-color 0.3s;
        }

        .form-input:focus {
            outline: none;
            border-color: #667eea;
        }

        .form-textarea {
            width: 100%;
            padding: 12px;
            border: 2px solid #e0e0e0;
            border-radius: 5px;
            font-size: 16px;
            min-height: 120px;
            resize: vertical;
            transition: border-color 0.3s;
        }

        .form-textarea:focus {
            outline: none;
            border-color: #667eea;
        }

        .modal-actions {
            display: flex;
            justify-content: flex-end;
            gap: 15px;
            margin-top: 30px;
        }

        .btn {
            padding: 12px 25px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            transition: all 0.3s;
        }

        .btn-primary {
            background: #007bff;
            color: white;
        }

        .btn-primary:hover {
            background: #0056b3;
        }

        .btn-secondary {
            background: #6c757d;
            color: white;
        }

        .btn-secondary:hover {
            background: #545b62;
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="container">
            <h1>新闻资讯平台</h1>
        </div>
    </div>

    <div class="container">
        <!-- 搜索和添加区域 -->
        <div class="search-section">
            <form class="search-form" id="searchForm">
                <input type="text" class="search-input" id="searchInput" placeholder="请输入关键词搜索新闻...">
                <button type="submit" class="search-btn">搜索</button>
            </form>
            <div class="add-news-section">
                <button class="add-btn" onclick="showAddNewsModal()">+ 添加新闻</button>
            </div>
        </div>

        <!-- 新闻列表区域 -->
        <div class="news-section">
            <div class="section-title">最新新闻</div>
            <div class="news-list" id="newsList">
                <div class="loading">正在加载新闻...</div>
            </div>
            <div class="pagination" id="pagination" ">
                <button class="page-btn" onclick="goToPage(1)">首页</button>
                <button class="page-btn" onclick="goToPage(currentPage - 1)">上一页</button>
                <button class="page-btn" onclick="goToPage(currentPage + 1)">下一页</button>
            </div>
        </div>


    <!-- 添加/编辑新闻模态框 -->
    <div id="newsModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <div class="modal-title" id="modalTitle">添加新闻</div>
                <span class="close" onclick="closeNewsModal()">&times;</span>
            </div>
            <form id="newsForm">
                <input type="hidden" id="newsId" value="">
                <div class="form-group">
                    <label class="form-label" for="newsTitle">标题</label>
                    <input type="text" class="form-input" id="newsTitle" required>
                </div>
                <div class="form-group">
                    <label class="form-label" for="newsAuthor">作者</label>
                    <input type="text" class="form-input" id="newsAuthor" required>
                </div>
                <div class="form-group">
                    <label class="form-label" for="newsType">分类</label>
                    <input type="text" class="form-input" id="newsType" required>
                </div>
                <div class="form-group">
                    <label class="form-label" for="newsContent">内容</label>
                    <textarea class="form-textarea" id="newsContent" required></textarea>
                </div>
                <div class="modal-actions">
                    <button type="button" class="btn btn-secondary" onclick="closeNewsModal()">取消</button>
                    <button type="submit" class="btn btn-primary">保存</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        let currentPage = 1;
        const pageSize = 10;

        // 页面加载完成后获取新闻列表
        document.addEventListener('DOMContentLoaded', function() {
            loadNewsList(currentPage);
        });

        // 搜索表单提交事件
        document.getElementById('searchForm').addEventListener('submit', function(e) {
            e.preventDefault();
            const keyword = document.getElementById('searchInput').value.trim();
            if (keyword) {
                searchNews(keyword);
            }
        });

        // 加载新闻列表
        async function loadNewsList(page) {
            try {
                showLoading();
                const response = await fetch('/news/list', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: `pageNum=${page}&pageSize=${pageSize}`
                });
                
                const result = await response.json();
                
                if (result.code === 200) {
                    displayNewsList(result.data);
                    currentPage = page;
                } else {
                    showError('加载新闻失败: ' + result.message);
                }
            } catch (error) {
                showError('网络错误: ' + error.message);
            }
        }

        // 搜索新闻
        async function searchNews(keyword) {
            try {
                showLoading();
                const response = await fetch('/news/search', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: `keyword=${encodeURIComponent(keyword)}`
                });
                
                const result = await response.json();
                
                if (result.code === 200) {
                    displaySearchResults(result.data, keyword);
                } else {
                    showError('搜索失败: ' + result.message);
                }
            } catch (error) {
                showError('搜索出错: ' + error.message);
            }
        }

        // 显示新闻列表
        function displayNewsList(newsList) {
            const newsListElement = document.getElementById('newsList');
            
            if (!newsList || newsList.length === 0) {
                newsListElement.innerHTML = '<div class="no-data">暂无新闻数据</div>';
                document.getElementById('pagination').style.display = 'none';
                return;
            }

            let html = '';
            newsList.forEach(news => {
                html += `
                    <div class="news-item">
                        <div class="news-content" onclick="viewNewsDetail(${news.id})">
                            <div class="news-title">${news.title || '无标题'}</div>
                            <div class="news-meta">
                                <span>作者: ${news.author || '未知'}</span>
                                <span>分类: ${news.type || '未分类'}</span>
                            </div>
                            <div class="news-summary">${news.content ? news.content.substring(0, 150) + '...' : '暂无内容'}</div>
                        </div>
                        <div class="news-actions">
                            <button class="action-btn edit-btn" onclick="editNews(${news.id}, '${news.title || ''}', '${news.author || ''}', '${news.type || ''}', '${news.content || ''}')">修改</button>
                            <button class="action-btn delete-btn" onclick="deleteNews(${news.id})">删除</button>
                        </div>
                    </div>
                `;
            });

            newsListElement.innerHTML = html;
        }

        // 显示搜索结果
        function displaySearchResults(newsList, keyword) {
            const newsListElement = document.getElementById('newsList');

            console.log('搜索结果:', newsList); // 调试日志
            
            if (!newsList || newsList.length === 0) {
                newsListElement.innerHTML = `<div class="no-data">未找到包含"${keyword}"的新闻</div>`;
                return;
            }

            let html = '';
            newsList.forEach(news => {
                html += `
                    <div class="news-item">
                        <div class="news-content" onclick="viewNewsDetail(${news.id})">
                            <div class="news-title">${highlightKeyword(news.title || '无标题', keyword)}</div>
                            <div class="news-meta">
                                <span>作者: ${highlightKeyword(news.author || '未知', keyword)}</span>
                                <span>分类: ${highlightKeyword(news.type || '未分类', keyword)}</span>
                            </div>
                            <div class="news-summary">${highlightKeyword(news.content ? news.content.substring(0, 150) + '...' : '暂无内容', keyword)}</div>
                        </div>
                        <div class="news-actions">
                            <button class="action-btn edit-btn" onclick="editNews(${news.id}, '${news.title || ''}', '${news.author || ''}', '${news.type || ''}', '${news.content || ''}')">修改</button>
                            <button class="action-btn delete-btn" onclick="deleteNews(${news.id})">删除</button>
                        </div>
                    </div>
                `;
            });

            newsListElement.innerHTML = html;
        }

        // 高亮关键词
        function highlightKeyword(text, keyword) {
            if (!keyword) return text;
            const regex = new RegExp(`(${keyword})`, 'gi');
            return text.replace(regex, '<mark style="background-color: #ffeb3b; padding: 2px 4px;">$1</mark>');
        }

        // 查看新闻详情
        function viewNewsDetail(newsId) {
            window.location.href = `search_details.html?id=${newsId}`;
        }

        // 格式化日期
        function formatDate(dateString) {
            if (!dateString) return '未知时间';
            const date = new Date(dateString);
            return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN');
        }

        // 显示加载状态
        function showLoading() {
            document.getElementById('newsList').innerHTML = '<div class="loading">正在加载...</div>';
        }

        // 显示错误信息
        function showError(message) {
            document.getElementById('newsList').innerHTML = `<div class="error">${message}</div>`;
        }

        // 分页功能
        function goToPage(page) {
            loadNewsList(page);
        }

        // 显示添加新闻模态框
        function showAddNewsModal() {
            document.getElementById('modalTitle').textContent = '添加新闻';
            document.getElementById('newsId').value = '';
            document.getElementById('newsTitle').value = '';
            document.getElementById('newsAuthor').value = '';
            document.getElementById('newsType').value = '';
            document.getElementById('newsContent').value = '';
            document.getElementById('newsModal').style.display = 'block';
        }

        // 编辑新闻
        function editNews(id, title, author, type, content) {
            // 清理高亮标签
            title = stripHtml(title);
            author = stripHtml(author);
            type = stripHtml(type);
            content = stripHtml(content)

            document.getElementById('modalTitle').textContent = '编辑新闻';
            document.getElementById('newsId').value = id;
            document.getElementById('newsTitle').value = title;
            document.getElementById('newsAuthor').value = author;
            document.getElementById('newsType').value = type;
            document.getElementById('newsContent').value = content;
            document.getElementById('newsModal').style.display = 'block';
        }
        function stripHtml(html) {
            const temp = document.createElement("div");
            temp.innerHTML = html;
            return temp.textContent || temp.innerText || "";
        }

        // 关闭模态框
        function closeNewsModal() {
            document.getElementById('newsModal').style.display = 'none';
        }

        // 删除新闻
        async function deleteNews(newsId) {
            if (!confirm('确定要删除这条新闻吗？')) {
                return;
            }

            try {
                console.log('删除新闻ID:', newsId); // 调试日志
                const response = await fetch('/news/delete', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: `newsId=${newsId}`
                });
                
                const result = await response.json();
                console.log('删除结果:', result); // 调试日志
                
                if (result.code === 200) {
                    alert('删除成功！');
                    loadNewsList(currentPage); // 重新加载当前页
                } else {
                    alert('删除失败: ' + result.message);
                }
            } catch (error) {
                console.error('删除错误:', error); // 调试日志
                alert('删除出错: ' + error.message);
            }
        }

        // 表单提交处理
        document.getElementById('newsForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const newsId = document.getElementById('newsId').value;
            const title = document.getElementById('newsTitle').value;
            const author = document.getElementById('newsAuthor').value;
            const type = document.getElementById('newsType').value;
            const content = document.getElementById('newsContent').value;

            if (!title || !author || !type || !content) {
                alert('请填写所有必填字段！');
                return;
            }

            const newsData = {
                id: newsId ? parseInt(newsId) : null,
                title: title,
                author: author,
                type: type,
                content: content
            };

            try {
                const url = newsId ? '/news/update' : '/news/publish';
                const response = await fetch(url, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(newsData)
                });
                
                const result = await response.json();
                
                if (result.code === 200) {
                    alert(newsId ? '修改成功！' : '添加成功！');
                    closeNewsModal();
                    loadNewsList(currentPage); // 重新加载当前页
                } else {
                    alert((newsId ? '修改' : '添加') + '失败: ' + result.message);
                }
            } catch (error) {
                alert((newsId ? '修改' : '添加') + '出错: ' + error.message);
            }
        });

        // 点击模态框外部关闭
        window.onclick = function(event) {
            const modal = document.getElementById('newsModal');
            if (event.target === modal) {
                closeNewsModal();
            }
        }
    </script>
</body>
</html>